import api from '@/api'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    id: null,
    username: '',
    realname: '',
    email: '',
    avatar: '',
    roles: [],
    permissions: []
  })

  const isLoggedIn = ref(false)

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const { data: res } = await api.getUserInfo()
      if (res?.code === 200 && res?.data) {
        userInfo.value = {
          id: res.data.id,
          username: res.data.username,
          realname: res.data.realname,
          email: res.data.email,
          avatar: res.data.avatar || '',
          roles: res.data.roles || [],
          permissions: res.data.permissions || []
        }
        isLoggedIn.value = true
        return true
      } else {
        console.error('获取用户信息失败:', res?.message)
        return false
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {
      id: null,
      username: '',
      realname: '',
      email: '',
      avatar: '',
      roles: [],
      permissions: []
    }
    isLoggedIn.value = false
  }

  // 设置用户信息
  const setUserInfo = data => {
    userInfo.value = { ...userInfo.value, ...data }
    isLoggedIn.value = true
  }

  return {
    userInfo,
    isLoggedIn,
    fetchUserInfo,
    clearUserInfo,
    setUserInfo
  }
})
